package com.example.demo.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import java.util.LinkedList;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.Fabric;
import com.example.demo.service.ProxyReEncrypt;
import com.example.demo.service.PubParams;
import com.example.demo.service.SystemProperty;

import it.unisa.dia.gas.jpbc.Element;
@RestController
public class FabricController {
	private static Fabric f;
	

	
	 static  {//系统初始化
		ProxyReEncrypt  d=new ProxyReEncrypt ();		
		int m=5,t=3;
		SimpleEntry<PubParams,Element> retMap=d.setup();
		PubParams p=retMap.getKey();
		d.save(p);
		SystemProperty.writeProperties("m", "5");
		SystemProperty.writeProperties("t", "3");
		f=new Fabric(p,m,t,retMap.getValue());
	}
	@RequestMapping(value = "/ids", method = { RequestMethod.GET })
	public List<String> getIDs() {//ALICE 
		List<Element> ids=f.getIDs();
		List<String> idbytes=new LinkedList<>();
    	for(Element id:ids) {
    		try {
				idbytes.add(new String(id.toBytes(),"ISO-8859-1"));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
		return idbytes;
	}
	@GetMapping(value = "/rkGen", produces = "application/json")
	public LinkedList<String> RkGen() {// BOB 请求
		return f.KeyGen();
	}
	
	@RequestMapping(value = "/A", method = { RequestMethod.POST })
	public String setA(@RequestBody List<String> receivers) {// ALICE 请求
		//System.out.println(f.mu.size());
		List<Element> ids=new LinkedList<>();
		for(int i=0;i<receivers.size();i++) {
			Element id = null;
			
			BigInteger b=new BigInteger(receivers.get(i));
			//System.out.println(b);
			id = f.p.Zr.newElementFromBytes(b.toByteArray());
			
			ids.add(id);
		}
		 f.setA(ids);
		 try {
			return new String(f.getA().toBytes(),"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return "";
	}
	@RequestMapping(value = "/A", method = { RequestMethod.GET })
	public String getA() {// BOB请求
		try {
			return new String(f.getA().toBytes(),"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return "";
	}
}
